from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
import os

from .performance_comparison import collect_results


def create_word_document(results, filename):
    doc = Document()
    doc.add_heading('仿真结果比较', level=1)

    for i, result in enumerate(results, start=1):
        doc.add_heading(f'模型 {i}: {result.model_name}', level=2)

        table = doc.add_table(rows=1, cols=4)
        hdr_cells = table.rows[0].cells
        hdr_cells[0].text = '描述'
        hdr_cells[1].text = 'Dymola 运行时间 (s)'
        hdr_cells[2].text = 'ZQ 运行时间 (s)'
        hdr_cells[3].text = 'F 函数调用次数'

        row_cells = table.add_row().cells
        row_cells[0].text = '仿真总时间'
        row_cells[1].text = f"{result.dymola_result.cpu_time_integration}"
        row_cells[2].text = f"{result.zq_result.total_time}"
        row_cells[3].text = f"{result.dymola_result.f_evaluations}"

        row_cells = table.add_row().cells
        row_cells[0].text = '非线性迭代次数'
        row_cells[1].text = f"{result.dymola_result.non_linear_iterations}"
        row_cells[2].text = f"{result.zq_result.nniters}"
        row_cells[3].text = f"{result.dymola_result.non_linear_iterations}"

        doc.add_paragraph()

    doc.save(filename)
    print(f"Word document '{filename}' has been created successfully.")


if __name__ == "__main__":
    dymola_directory = r"D:\pyProject\dymola_test\dymola_test\dymola_res"
    zq_directory = r"D:\pyProject\dymola_test\dymola_test\zq_res"
    all_results = collect_results(dymola_directory, zq_directory)

    word_filename = os.path.join(os.getcwd(), "Simulation_Results_Document.docx")
    create_word_document(all_results, word_filename)
